package com.lingshu.app.ui.login;

import androidx.lifecycle.ViewModelProvider;

import com.lingshu.app.R;
import com.lingshu.app.base.BaseActivity;
import com.lingshu.app.config.App;
import com.lingshu.app.config.Constants;
import com.lingshu.app.config.LoadState;
import com.lingshu.app.databinding.ActivityLoginBinding;
import com.lingshu.app.model.auth.LoginBean;
import com.lingshu.app.ui.main.MainActivity;

import dagger.hilt.android.AndroidEntryPoint;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2023/12/28 13:58
 * @Description
 */
@AndroidEntryPoint
public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> {
    /**
     * 获取当前页面的布局资源ID
     *
     * @return 布局资源ID
     */
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    /**
     * 初始化ViewModel
     */
    @Override
    protected void initViewModel() {
        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
    }

    /**
     * 绑定ViewModel
     */
    @Override
    protected void bindViewModel() {
        dataBinding.setViewModel(viewModel);
    }

    /**
     * 初始化
     */
    @Override
    protected void init() {
        String account = App.getMvUtils().getString(Constants.USER_ACCOUNT);
        String password = App.getMvUtils().getString(Constants.USER_PASSWORD);
        LoginBean userBean = new LoginBean(account, password);
        viewModel.getLoginInfo().postValue(userBean);
        viewModel.loadState.postValue(LoadState.SUCCESS);
        viewModel.loginResult.observe(this, returnResult -> {
            if (returnResult.getSuccess()) {
                App.getMvUtils().put(Constants.USER_ID, returnResult.getData().getUserId());
                App.getMvUtils().put(Constants.USER_NAME, returnResult.getData().getName());
                App.getMvUtils().put(Constants.USER_ACCOUNT, returnResult.getData().getAccount());
                App.getMvUtils().put(Constants.USER_PASSWORD, userBean.getPassword());
                App.getMvUtils().put(Constants.USER_TOKEN, returnResult.getData().getToken());
                App.getMvUtils().put(Constants.USER_TYPE, returnResult.getData().getUserType());

                jumpActivity(MainActivity.class);
            } else {
                viewModel.infoMsg.postValue(returnResult.getMessage());
            }
        });
    }
}
